<template>
  <div class="set">
    <div class="breadcrumb">
      <el-icon>
        <Location />
      </el-icon>
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>系统设置</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <el-tabs v-model="activeName" class="demo-tabs">
      <el-tab-pane label="账号详情" name="first" v-loading="accountDetailsLoading">
        <div class="itemWrap">
          <span>用户头像：</span>
          <el-upload
            name="imageUrl"
            class="avatar-uploader"
            action="http://127.0.0.1:7001/userInfo/uploadAvatar"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :headers="headers"
          >
            <img v-if="accountDetails.imageUrl" :src="accountDetails.imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </div>
        <div class="itemWrap">
          <span>用户账户：</span>
          <el-input v-model="accountDetails.account" disabled style="width:300px" />
        </div>
        <div class="itemWrap">
          <span>用户密码：</span>
          <el-button type="primary" @click="changePasswordDialogVisible = true">修改密码</el-button>
        </div>
        <div class="itemWrap">
          <span>用户姓名：</span>
          <el-input
            v-model="accountDetails.name"
            placeholder="请输入姓名"
            style="width:300px;margin-right:10px;"
          />
          <el-button type="primary" @click="toChangeName()">保存</el-button>
        </div>
        <div class="itemWrap">
          <span>用户性别：</span>
          <el-select
            v-model="accountDetails.sex"
            class="m-2"
            placeholder="请选择性别"
            style="width:300px;margin-right:10px;"
          >
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
          <el-button type="primary" @click="toChangeSex()">保存</el-button>
        </div>
        <div class="itemWrap">
          <span>用户身份：</span>
          <el-input
            v-model="accountDetails.identity"
            disabled
            style="width:300px;margin-right:10px;"
          />
        </div>
        <div class="itemWrap">
          <span>用户部门：</span>
          <el-input
            v-model="accountDetails.department"
            disabled
            style="width:300px;margin-right:10px;"
          />
        </div>
        <div class="itemWrap">
          <span>用户邮箱：</span>
          <el-input
            v-model="accountDetails.email"
            placeholder="请输入邮箱"
            style="width:300px;margin-right:10px;"
          />
          <el-button type="primary" @click="toChangeEmail()">保存</el-button>
        </div>
      </el-tab-pane>
      <el-tab-pane label="公司信息" name="second">
        <div class="itemWrap">
          <span>公司名称：</span>
          <el-input
            v-model="corporateName"
            placeholder="请输入姓名"
            style="width:300px;margin-right:10px;"
          />
          <el-button type="primary" @click="toChangeCorporateName()">编辑公司名称</el-button>
        </div>
        <div class="itemWrap">
          <span>公司介绍：</span>
          <el-button type="primary" @click="toShow(1)">编辑公司介绍</el-button>
        </div>
        <div class="itemWrap">
          <span>用户架构：</span>
          <el-button type="primary" @click="toShow(2)">编辑用户架构</el-button>
        </div>
        <div class="itemWrap">
          <span>用户战略：</span>
          <el-button type="primary" @click="toShow(3)">编辑用户战略</el-button>
        </div>
        <div class="itemWrap">
          <span>现任高层：</span>
          <el-button type="primary" @click="toShow(4)">编辑现任高层</el-button>
        </div>
      </el-tab-pane>
      <el-tab-pane label="首页管理" name="third">
        <el-row :gutter="20">
          <el-col :span="8" v-for="(item, index) in swiperList" :key="index">
            <div class="itemWrap swiperWrap">
              <span>轮播图{{index + 1}}：</span>
              <el-upload
                name="imageUrl"
                class="avatar-uploader"
                action="http://127.0.0.1:7001/setting/setSwiper"
                :data="{name: 'swiper' + (index + 1)}"
                :show-file-list="false"
                :on-success="handleAvatarSuccessSwiper"
                :before-upload="beforeAvatarUpload"
                :headers="headers"
              >
                <img
                  v-if="item.set_value"
                  :src="'http://127.0.0.1:7001' + item.set_value"
                  class="avatar"
                />
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>
            </div>
          </el-col>
        </el-row>
      </el-tab-pane>
      <el-tab-pane label="其他设置" name="fourth">
        <div class="typeWrap">
          <span style="margin-right:10px">部门：</span>
          <el-tag
            v-for="tag in dynamicTags"
            :key="tag.id"
            class="mx-1"
            closable
            :disable-transitions="false"
            @close="handleClose(tag)"
          >{{ tag.name }}</el-tag>
          <el-input
            style="width:200px;margin-bottom:5px;"
            v-if="inputVisible"
            ref="InputRef"
            v-model="inputValue"
            class="ml-1 w-20"
            size="small"
            @keyup.enter="handleInputConfirm"
            @blur="handleInputConfirm"
          />
          <el-button
            style="margin-bottom:5px;"
            v-else
            class="button-new-tag ml-1"
            size="small"
            @click="showInput"
          >+ 新增</el-button>
        </div>
        <div class="typeWrap">
          <span style="margin-right:10px">产品类型：</span>
          <el-tag
            v-for="tag in dynamicTags1"
            :key="tag.id"
            class="mx-1"
            closable
            :disable-transitions="false"
            @close="handleClose1(tag)"
          >{{ tag.name }}</el-tag>
          <el-input
            style="width:200px;margin-bottom:5px;"
            v-if="inputVisible1"
            ref="InputRef1"
            v-model="inputValue1"
            class="ml-1 w-20"
            size="small"
            @keyup.enter="handleInputConfirm1"
            @blur="handleInputConfirm1"
          />
          <el-button
            style="margin-bottom:5px;"
            v-else
            class="button-new-tag ml-1"
            size="small"
            @click="showInput1"
          >+ 新增</el-button>
        </div>
      </el-tab-pane>
    </el-tabs>
    <el-dialog draggable v-model="changePasswordDialogVisible" title="修改密码" width="30%">
      <el-form ref="resettingRef" :rules="resettingRules" :model="resetting" label-width="80px">
        <el-form-item label="原先密码" prop="oldPassword">
          <el-input v-model="resetting.oldPassword" placeholder="原先密码" />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="resetting.newPassword" placeholder="新密码" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="changePasswordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="changePasswordOK()" :loading="changePasswordLoading">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog
      draggable
      @close="corporateClose"
      v-model="corporateDialogVisible"
      :title="corporateContent.title"
      width="30%"
    >
      <div style="border: 1px solid #ccc" v-if="corporateDialogVisible">
        <Toolbar
          style="border-bottom: 1px solid #ccc"
          :editor="editorRef"
          :defaultConfig="toolbarConfig"
          :mode="mode"
        />
        <Editor
          style="height: 500px; overflow-y: hidden;"
          v-model="corporateContent.content"
          :defaultConfig="editorConfig"
          :mode="mode"
          @onCreated="handleCreated"
        />
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="corporateDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="corporateOK()" :loading="corporateLoading">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>


<script setup>
import {
  onBeforeUnmount,
  ref,
  shallowRef,
  reactive,
  toRefs,
  onMounted,
  nextTick,
  computed,
  defineProps
} from "vue";

// // //这里名字无所谓, 就是待会new的时候要用这个名字new
// // import EWangEditor from "wangeditor";
// import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

import "@wangeditor/editor/dist/css/style.css"; // 引入 css

import { Editor, Toolbar } from "@wangeditor/editor-for-vue";

import {
  userInfo,
  changePassword,
  changeName,
  changeSex,
  changeEmail,
  getCorporateName,
  changeCorporateName,
  getCorporateInfo,
  setCorporateInfo,
  getSwiper,
  getDepartment,
  addDepartment,
  deleteDepartment,
  getProductType,
  addProductType,
  deleteProductType
} from "@/api/user";

import { useRouter } from "vue-router";

// 调用store树中内容需要引入
import { useStore } from "vuex";
// 获取store
const store = useStore();

import { ElMessage } from "element-plus";
const router = useRouter();
import {
  Document,
  Menu as IconMenu,
  Location,
  Setting,
  House,
  Message,
  Grid,
  Avatar,
  Position,
  ChatLineSquare,
  Notification,
  Notebook,
  Plus
} from "@element-plus/icons-vue";
const activeName = ref("first");

const handleAvatarSuccess = (response, uploadFile) => {
  accountDetails.imageUrl = URL.createObjectURL(uploadFile.raw);
  store.commit("setImageUrl", response.data);
};
const handleAvatarSuccessSwiper = (response, uploadFile) => {
  togetSwiper();
  // accountDetails.imageUrl = URL.createObjectURL(uploadFile.raw);
  // store.commit("setImageUrl", response.data);
};
const headers = reactive({
  Authorization: localStorage.getItem("token")
});
const beforeAvatarUpload = rawFile => {
  if (rawFile.type !== "image/jpeg") {
    ElMessage.error("图片必须是jpg");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("图片大小不能超过2MB!");
    return false;
  }
  return true;
};
const accountDetails = reactive({
  imageUrl: store.state.imageUrl,
  account: store.state.account,
  name: store.state.name,
  sex: store.state.sex,
  identity: store.state.identity,
  department: store.state.department,
  email: store.state.email
});
const accountDetailsLoading = ref(false);
// const getUserInfo = () => {
//   accountDetailsLoading.value = true;
//   userInfo()
//     .then(res => {
//       if (res.data.status != 0) {
//         return ElMessage.error(res.data.message);
//       }
//       ElMessage.success(res.data.message);
//       // accountDetails = res.data.data;
//       accountDetails.account = res.data.data.account;
//       accountDetails.name = res.data.data.name;
//       accountDetails.sex = res.data.data.sex;
//       accountDetails.identity = res.data.data.identity;
//       accountDetails.department = res.data.data.department;
//       accountDetails.email = res.data.data.email;
//       accountDetails.imageUrl =
//         "http://127.0.0.1:7001" + res.data.data.imageUrl;

//       // imageUrl.value = res.data.data.imageUrl
//       console.log(accountDetails);
//     })
//     .finally(() => {
//       accountDetailsLoading.value = false;
//     });
// };

const changePasswordDialogVisible = ref(false);
const resetting = reactive({
  oldPassword: "",
  newPassword: ""
});
const resettingRules = reactive({
  oldPassword: [{ required: true, message: "请填写原先密码", trigger: "blur" }],
  newPassword: [{ required: true, message: "请填写新密码", trigger: "blur" }]
});

const resettingRef = ref();
const changePasswordLoading = ref(false);
const changePasswordOK = () => {
  resettingRef.value.validate((valid, fields) => {
    if (valid) {
      let data = {
        oldPassword: resetting.oldPassword,
        newPassword: resetting.newPassword
      };
      changePasswordLoading.value = true;
      changePassword(data)
        .then(res => {
          if (res.data.status != 0) {
            return ElMessage.error(res.data.message);
          }
          ElMessage.success(res.data.message);
          changePasswordDialogVisible.value = false;
          setTimeout(() => {
            router.replace("/login");
          }, 200);
        })
        .finally(() => {
          changePasswordLoading.value = false;
        });
    } else {
      console.log("error submit!", fields);
    }
  });
};

const toChangeName = () => {
  if (!accountDetails.name) {
    return ElMessage.error("请输入名称");
  }

  let data = {
    name: accountDetails.name
  };

  changeName(data).then(res => {
    if (res.data.status != 0) {
      return ElMessage.error(res.data.message);
    }
    store.commit("setName", accountDetails.name);
    ElMessage.success(res.data.message);
  });
};

const toChangeSex = () => {
  if (!accountDetails.sex) {
    return ElMessage.error("请输入性别");
  }
  let data = {
    sex: accountDetails.sex
  };
  changeSex(data).then(res => {
    if (res.data.status != 0) {
      return ElMessage.error(res.data.message);
    }
    store.commit("setSex", accountDetails.sex);
    ElMessage.success(res.data.message);
  });
};

const toChangeEmail = () => {
  if (!accountDetails.email) {
    return ElMessage.error("请输入email");
  }
  let data = {
    email: accountDetails.email
  };
  changeEmail(data).then(res => {
    if (res.data.status != 0) {
      return ElMessage.error(res.data.message);
    }
    store.commit("setEmail", accountDetails.email);
    ElMessage.success(res.data.message);
  });
};
const corporateName = ref("");
const togetCorporateName = () => {
  let query = {
    name: "公司名称"
  };
  getCorporateName(query).then(res => {
    if (res.data.status != 0) {
      return ElMessage.error(res.data.message);
    }
    corporateName.value = res.data.data.set_value;
  });
};
const toChangeCorporateName = () => {
  if (!corporateName.value) {
    return ElMessage("请填写公司名称");
  }
  let data = {
    content: corporateName.value
  };
  changeCorporateName(data).then(res => {
    if (res.data.status != 0) {
      return ElMessage.error(res.data.message);
    }
    ElMessage.success(res.data.message);
  });
};

const corporateDialogVisible = ref(false);

const corporateLoading = ref(false);
const corporateContent = reactive({
  title: "",
  content: ""
});

const toShow = n => {
  let name = "";
  if (n == 1) {
    name = "公司介绍";
  } else if (n == 2) {
    name = "公司架构";
  } else if (n == 3) {
    name = "公司战略";
  } else if (n == 4) {
    name = "公司高管";
  }
  let query = {
    name: name
  };
  getCorporateInfo(query).then(res => {
    if (res.data.status != 0) {
      return ElMessage.error(res.data.message);
    }
    corporateContent.title = res.data.data.set_name;
    corporateContent.content = res.data.data.set_text;
    corporateDialogVisible.value = true;
  });
};
const corporateClose = () => {
  editorRef.value = null; // 记录 editor 实例，重要！
};
const corporateOK = () => {
  let data = {
    name: corporateContent.title,
    content: corporateContent.content
  };
  setCorporateInfo(data).then(res => {
    if (res.data.status != 0) {
      return ElMessage.error(res.data.message);
    }
    ElMessage.success(res.data.message);
    corporateDialogVisible.value = false;
  });
};

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();
// mode
const mode = ref("default");
// 内容 HTML
// const valueHtml = ref();
const toolbarConfig = {
  excludeKeys: []
};
const editorConfig = {
  placeholder: "请输入内容...",
  MENU_CONF: {
    uploadImage: {
      //上传图片配置
      server: "http://127.0.0.1:3007/set/uploadCompanyPicture", //上传接口地址
      fieldName: "file", //上传文件名
      methods: "post",
      metaWithUrl: true, // 参数拼接到 url 上
      // 单个文件上传成功之后
      // onSuccess(file, res) {
      // },
      // 自定义插入图片
      customInsert(res, insertFn) {
        insertFn(res.url);
      }
    }
  }
};
// 上传图片，修改 uploadImage 菜单配置
// 需要注意的是，如何去修改参数？
toolbarConfig.excludeKeys = [
  "blockquote",
  "bgColor",
  "color",
  "group-more-style",
  "fontFamily",
  "bulletedList",
  "numberedList",
  "lineHeight",
  "todo",
  "emotion",
  "insertLink",
  "group-video",
  "insertTable",
  "codeBlock",
  "divider",
  "fullScreen"
  // 'group-image',

  // 排除菜单组，写菜单组 key 的值即可
];

const handleCreated = editor => {
  console.log(editor, "editoreditor");
  editorRef.value = editor; // 记录 editor 实例，重要！
};
const swiperList = ref([]);
const togetSwiper = () => {
  getSwiper().then(res => {
    if (res.data.status != 0) {
      return ElMessage.error(res.data.message);
    }
    swiperList.value = res.data.data;
  });
};




const inputValue = ref("");
const dynamicTags = ref([]);
const inputVisible = ref(false);
const InputRef = ref();

const handleClose = tag => {
  let data = {
    id: tag.id
  };
  deleteDepartment(data).then(res => {
    if (res.data.status != 0) {
      return ElMessage.error(res.data.message);
    }
    togetDepartment();
  });
  // dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1);
};

const showInput = () => {
  inputVisible.value = true;
  nextTick(() => {
    InputRef.value.input.focus();
  });
};

const handleInputConfirm = () => {
  if (!inputValue.value) {
    inputVisible.value = false;
    inputValue.value = "";
    return;
  }
  let data = {
    name: inputValue.value
  };
  addDepartment(data).then(res => {
    if (res.data.status != 0) {
      return ElMessage.error(res.data.message);
    }
    togetDepartment();
    inputVisible.value = false;
    inputValue.value = "";
  });
};

const togetDepartment = () => {
  getDepartment().then(res => {
    if (res.data.status != 0) {
      return;
    }
    dynamicTags.value = res.data.data;
  });
};


const inputValue1 = ref("");
const dynamicTags1 = ref([]);
const inputVisible1 = ref(false);
const InputRef1 = ref();

const handleClose1 = tag => {
  let data = {
    id: tag.id
  };
  deleteProductType(data).then(res => {
    if (res.data.status != 0) {
      return ElMessage.error(res.data.message);
    }
    togetDepartment1();
  });
};

const showInput1 = () => {
  inputVisible1.value = true;
  nextTick(() => {
    InputRef1.value.input.focus();
  });
};

const handleInputConfirm1 = () => {
  if (!inputValue1.value) {
    inputVisible1.value = false;
    inputValue1.value = "";
    return;
  }
  let data = {
    name: inputValue1.value
  };
  addProductType(data).then(res => {
    if (res.data.status != 0) {
      return ElMessage.error(res.data.message);
    }
    togetDepartment1();
    inputVisible1.value = false;
    inputValue1.value = "";
  });
};

const togetDepartment1 = () => {
  getProductType().then(res => {
    if (res.data.status != 0) {
      return;
    }
    dynamicTags1.value = res.data.data;
  });
};

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

onMounted(() => {
  togetCorporateName();
  togetSwiper();
  togetDepartment();
  togetDepartment1(); 
});
</script>

<style scoped lang="scss">
.set {
  .breadcrumb {
    display: flex;
  }
  .itemWrap {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
  }
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}
</style>
<style lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.swiperWrap {
  .avatar-uploader {
    flex: 1;
    .el-upload {
      width: 100%;
      height: 200px;

      .avatar {
        width: 100%;
        height: 100%;
        display: block;
        object-fit: cover;
      }
    }
  }
}

.typeWrap{
  margin-bottom:10px;
}
.el-tag {
  margin-right: 10px;
  margin-bottom: 5px;
}
</style>